package cn.sunlight.mm.service.impl;

import cn.sunlight.framework.annotation.HmComponent;
import cn.sunlight.mm.base.BaseService;
import cn.sunlight.mm.dao.RoleDao;
import cn.sunlight.mm.dao.UserDao;
import cn.sunlight.mm.dao.permissionDao;
import cn.sunlight.mm.database.MmDaoException;
import cn.sunlight.mm.database.SqlSessionUtils;
import cn.sunlight.mm.pojo.Permission;
import cn.sunlight.mm.pojo.Role;
import cn.sunlight.mm.pojo.User;
import cn.sunlight.mm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sunlight
 * @description:
 * @date 2021/5/18
 * @Version v1.0
 */
@Slf4j
@HmComponent("userService")
public class UserServiceImpl extends BaseService implements UserService {

    @Override
    public User findUserByUsermame(String username) {
        log.debug("UserServiceImpl...username:{}",username);
        //调用dao
        SqlSession sqlSession = SqlSessionUtils.openSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user=userDao.selectUserByUsername(username);
        return user;
    }

    @Override
    public List<String> getAuthList(Integer id) {
        //通过dao获取角色及权限列表
        //通过id，获取角色列表
        //通过角色列表获取每个角色的权限列表
        try {
            List<String> authList=new ArrayList<>();
            SqlSession session = getSession();
            RoleDao roleDao = getDao(session, RoleDao.class);
            permissionDao permissionDao = getDao(session, permissionDao.class);
            List<Role> roles = roleDao.selectListByUserId(id);
            //提取角色的keyword，放入权限列表
            for (Role role:roles){
                // ROLE_QUESTION_RECORDER
                authList.add(role.getKeyword());
                //根据当前角色id，获取权限列表
                List<Permission> permissions = permissionDao.selectListByRoleId(role.getId());
                // 遍历权限列表，把每个权限keyword放入authList
                for (Permission permission:permissions){
                    authList.add(permission.getKeyword());
                }
            }
            log.debug("获取用户ID:{},authList:{}",id,authList);
            return authList;
        }catch (MmDaoException e){
            e.printStackTrace();
            log.error(e.getMessage());
            throw new MmDaoException(e.getMessage());
        }

    }
}
